/**
 * 数据管理控制层
 */
define([ "app", "jquery", "md5", "ecb", 
        "services/UserService",
		"resources/UserResource", 
		'directives/InfiniteScroll',
		'directives/ColumnList',
		'directives/dataRecords/records',
		"directives/addCompany/AddCompany",
		'directives/addCompany/Company',
		"resources/DataRecordResource" ], function(app) {

	var deps = [ "$scope", "$state", "$modal","$location", "$stateParams","UserService","UserResource","DataRecordResource" ];

	function controller($scope, $state, $modal,$location, $stateParams,UserService,UserResource,DataRecordResource) {
		var pageNo = 1;
		var pageSize = 99999;
		queryDate();
		
		//var currentUser =UserService.getCurrentUser();
		$scope.changeLogoutImage =function (flag){
			var image =document.getElementById('imageChanges');
			if(flag){
				image.src="images/logout2.png";
			}else{
				image.src="images/logout1.png";
			}
		};
		
		$scope.changeChargeImage=function (flag){
			var image =document.getElementById('changeChargeImage');
			if(flag){
				image.src="images/charge2.png";
			}else{
				image.src="images/charge1.png";
			}
		};
		
		$scope.changeAddImage=function (flag){
			var image =document.getElementById('changeAddImage');
			if(flag){
				image.src="images/add2.png";
			}else{
				image.src="images/add1.png";
			}
		};
		
		$scope.addCompany=function addCompany($choseCompany){
			$scope.records=null;
			queryDate();
			//$scope.companys.push($choseCompany);
		};
		
		$scope.$on('companyFBroadCast', function($event,data) {
        	$scope.records=null;
			refreshDate(0,pageSize);
			$event.preventDefault();
        });
		
		/**
		 * 退出登陆
		 */
		$scope.logout = function() {
			UserResource.logout(function(){
				UserService.removeCurrentUser();
				$location.path("/login");
			});
		};
		
		$scope.scrollHandler = function scrollHandler() {
			pageNo++;
			queryDate().success(function loadedScrollCompanys(records) {
				if (records == null || records.length < pageSize) {
					$scope.scrollHandler = function noop() {};
				}
			});
		};
		
		$scope.$bus.subscribe({
			record: 'record',
			topic: 'remove',
			callback: function(id) {
				_.remove($scope.records, function(record) {
					return record.id === id;
				});
			}
		});
		
		// 初始化加载数据
		function queryDate(){
			return DataRecordResource.queryRecordList(pageNo,pageSize,null).success(function loadedCompanys(records) {
				$scope.records = $scope.records || [];
				[].push.apply($scope.records, records);
			});
		}
		
		//刷新数据
		function refreshDate(pageNo,pageSize){
			return DataRecordResource.queryRecordList(pageNo,pageSize,null).success(function loadedCompanys(records) {
				$scope.records = $scope.records || [];
				[].push.apply($scope.records, records);
			});
		}
	}
	controller.$inject = deps;
    return app.lazy.controller("DataManagementController", controller);
});
